package com.abe.libcore.base.http.interceptor

import android.text.TextUtils
import com.abe.libcore.utils.CommonUtils
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

class MoreBaseUrlInterceptor(private var moreBaseUrl: Array<MoreBaseUrlEntity>) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        try {
            //获取老的url
            val oldUrl = request.url
            //获取originalRequest的创建者builder
            val builder = request.newBuilder()
            //获取头信息的集合如：manage,mdffx
            val urlNameList = request.headers("urlName")
            if (urlNameList.isNotEmpty() && moreBaseUrl.isNotEmpty()) {
                //删除原有配置中的值,就是namesAndValues集合里的值
                builder.removeHeader("urlName")
                //获取头信息中配置的value,如：manage或者mdffx
                val urlName = urlNameList[0]
                var oldBaseUrl: HttpUrl? = null
                var baseURL: HttpUrl? = null
                val oldUrlStr: String = oldUrl.toString()
                //根据头信息中配置的value,来匹配新的base_url地址
                for (urlEntity: MoreBaseUrlEntity in moreBaseUrl) {
                    if (oldUrlStr.contains(urlEntity.urlValue)) {
                        oldBaseUrl = urlEntity.urlValue.toHttpUrlOrNull()
                    }
                    if (urlEntity.urlName == urlName) {
                        baseURL = urlEntity.urlValue.toHttpUrlOrNull()
                    }
                }
                try {
                    val middleStr = baseURL?.encodedPath ?: ""
                    val oldMiddleStr = oldBaseUrl?.encodedPath ?: ""
                    var apiPath = oldUrl.encodedPath
                    apiPath = if (!TextUtils.isEmpty(oldMiddleStr)) {
                        apiPath.replace(oldMiddleStr, middleStr)
                    } else {
                        middleStr + apiPath
                    }
                    //重建新的HttpUrl，需要重新设置的url部分
                    val urlBuilder = oldUrl.newBuilder()
                        .scheme(baseURL!!.scheme)//http协议如：http或者https
                        .host(baseURL.host)//主机地址
                        .port(baseURL.port)//端口
                        .encodedPath(apiPath)//路径
                    val newHttpUrl = urlBuilder.build()
                    //获取处理后的新newRequest
                    val newRequest = builder.url(newHttpUrl).build()
                    return chain.proceed(newRequest)
                } catch (nullE: NullPointerException) {
                    nullE.printStackTrace()
                }
                return chain.proceed(request)
            }
            return chain.proceed(request)
        } catch (e: Exception) {
            e.printStackTrace()
            CommonUtils.log("all-exception(MoreBaseUrlInterceptor):" + e.message)
            return chain.proceed(request.newBuilder().build())
        }
    }
}